package com.cloud.workTest;

import com.google.gson.Gson;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class DockerTest {

    public static void main(String[] args) {
        File tarGzFile = new File("C:\\Users\\86159\\Downloads\\gateway0417.tar.gz");
        try {
            // 解压缩 tar.gz 文件
            FileInputStream fileInputStream = new FileInputStream(tarGzFile);
            GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(fileInputStream);
            TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn);

            // 查找 repositories 文件
            TarArchiveEntry entry;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                if (!entry.isDirectory() && entry.getName().endsWith("/repositories")) {
                    // 找到 repositories 文件，解析镜像名和标签
                    Map<String, Map<String, String>> imageTagsMap = parseRepositoriesFile(tarIn);
                    for (Map.Entry<String, Map<String, String>> entrySet : imageTagsMap.entrySet()) {
                        String imageName = entrySet.getKey();
                        Map<String, String> tagsMap = entrySet.getValue();
                        for (Map.Entry<String, String> tagEntry : tagsMap.entrySet()) {
                            String tag = tagEntry.getKey();
                            String imageId = tagEntry.getValue();
                            System.out.println("Image Name: " + imageName + ", Tag: " + tag + ", Image ID: " + imageId);
                        }
                    }
                }
            }

            tarIn.close();
            gzipIn.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Map<String, String>> parseRepositoriesFile(InputStream inputStream) throws IOException {
        Map<String, Map<String, String>> imageTagsMap = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder jsonContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonContent.append(line);
            }
            // 解析 JSON
            String jsonString = jsonContent.toString();
            Map<String, Map<String, String>> repositories = new Gson().fromJson(jsonString, Map.class);
            for (Map.Entry<String, Map<String, String>> entry : repositories.entrySet()) {
                String imageName = entry.getKey();
                Map<String, String> tagsMap = entry.getValue();
                imageTagsMap.put(imageName, tagsMap);
            }
        }
        return imageTagsMap;
    }
}
